import unittest

import time

from twisted.internet import defer, reactor

from meercat.job.interfaces import IJob

from meercat.job.incremental import IncrementalJob



def testJobCallable(limit=0,offset=0):
    return limit + offset


def testDeferredFactory(f, *args, **kwargs):
    return defer.succeed(f(*args,**kwargs))

def testLimitFunction():
    return 1000

class InterfaceTestCase(unittest.TestCase):
    def testImplments(self):
        self.assert_(IJob.implementedBy(IncrementalJob))

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        pass
    
    def testSimpleRun(self):
        job = IncrementalJob(f=testJobCallable,limit=testLimitFunction,
                             offset=100,step=100,
                             max_workers=None,
                             deferredFactory=testDeferredFactory)
        job.start()
        self.assertEqual(job.getStatus(),
                         u'100.00% finished, 0.00% running, 0.00% pending (9, 0, 0)')
    
    def testLimitedRun(self):
        job = IncrementalJob(f=testJobCallable,limit=1000,
                             offset=0,step=100,
                             max_workers=2,
                             deferredFactory=testDeferredFactory)
        job.start()
        self.assertEqual(job.getStatus(),
                         u'100.00% finished, 0.00% running, 0.00% pending (10, 0, 0)')
    
    def testThreaded(self):
        job = IncrementalJob(f=testJobCallable,limit=1000,
                             offset=0,step=100,
                             max_workers=2)
        
        job.start()
        self.assertEqual(job.getStatus(),
                         u'0.00% finished, 20.00% running, 80.00% pending (0, 2, 8)')
        

def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.TestLoader().loadTestsFromTestCase(InterfaceTestCase))
  suite.addTest(unittest.TestLoader().loadTestsFromTestCase(BaseTestCase))
  return suite

if __name__ == '__main__':
  unittest.TextTestRunner(verbosity=2).run(test_suite())